#include <cstdio>
#include "../Thread.h"

namespace Anger
{
	static void RunThread(void* ptr)
	{
		auto thread = reinterpret_cast<Thread*>(ptr);
		auto callback = thread->GetCallback();
		if(callback==nullptr)
		{
            printf("thread callback is not null\n");
		}
		callback(thread);
	}
	
	bool Thread::Create(Callback cb, void* ud)
	{
		callback = cb;
		handle = nullptr;
		id = UINT32_MAX;
		userData = ud;
		handle = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)RunThread, this, 0, (DWORD*)&id);
		return IsCreated();
	}

	void Thread::SetAffinity(size_t offset)
	{
		if(!IsCreated())
		{
			return;
		}
		DWORD_PTR mask = 1ull << offset;
		SetThreadAffinityMask(handle, mask);
	}

	void Thread::Join()
	{
		if (!IsCreated())
		{
			return;
		}
		WaitForSingleObject(handle, INFINITE);
	}

	void Thread::Join(size_t ms)
	{
		if (!IsCreated())
		{
			return;
		}
		WaitForSingleObject(handle, ms);
	}

	void Thread::ConvertCurrentThread()
	{
		handle = GetCurrentThread();
		id = GetCurrentThreadId();
	}

	void Thread::ThreadSleep(uint32_t ms)
	{
		Sleep(ms);
	}
}
